package drds.binlog.parse.driver.utils;

import drds.binlog.parse.driver.packets.HeaderPacket;
import drds.binlog.parse.driver.socket.SocketChannel;

import java.io.IOException;

public abstract class Packets
{
    public static byte[] readBytes(SocketChannel socketChannel, int length) throws IOException
    {
        return socketChannel.read(length);
    }

    public static byte[] readBytes(SocketChannel socketChannel, int length, int timeout) throws IOException
    {
        return socketChannel.read(length, timeout);
    }

    public static HeaderPacket readHeader(SocketChannel socketChannel, int length) throws IOException
    {
        HeaderPacket headerPacket = new HeaderPacket();
        headerPacket.fromBytes(socketChannel.read(length));
        return headerPacket;
    }

    public static HeaderPacket readHeader(SocketChannel socketChannel, int length, int timeout) throws IOException
    {
        HeaderPacket headerPacket = new HeaderPacket();
        headerPacket.fromBytes(socketChannel.read(length, timeout));
        return headerPacket;
    }


    //
    public static void write(SocketChannel socketChannel, byte[]... bytes) throws IOException
    {
        socketChannel.write(bytes);
    }

    public static void writeBody(SocketChannel socketChannel, byte[] bytes) throws IOException
    {
        writeBody(socketChannel, bytes, (byte) 0);
    }

    public static void writeBody(SocketChannel socketChannel, byte[] bytes, byte packetSequenceNumber) throws IOException
    {
        HeaderPacket headerPacket = new HeaderPacket();
        headerPacket.setPacketBodyLength(bytes.length);
        headerPacket.setPacketSequenceNumber(packetSequenceNumber);
        socketChannel.write(headerPacket.toBytes(), bytes);
    }
}
